package com.mycompany.virtualApp.controller;

import com.mycompany.mvc.utils.BaseResult;
import com.mycompany.mvc.utils.SystemUtil;
import com.mycompany.virtualApp.Constants;
import com.mycompany.virtualApp.entity.*;
import com.mycompany.virtualApp.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Administrator on 2017/12/6 0006.
 * tab广告栏的controller
 */

@Controller
@RequestMapping("/tabAdv")
public class TabAdvController {

    Logger logger = LoggerFactory.getLogger(TabAdvController.class);

    @Autowired
    private TabAdvService tabAdvService;
    @Autowired
    private BannerAdvService bannerAdvService;
    @Autowired
    private DesktopAdvService desktopAdvService;
    @Autowired
    private ClickService clickService;
    /**
     * 获取数据
     */
    @RequestMapping("/getTabAdvList")
    @ResponseBody
    public Map<String,Object> getAllTabAdv(HttpServletRequest request) {
        String initValue = request.getParameter("initValue");
        List<TabAdvModel> listTab= new ArrayList<>();
        List<BannerAdvModel> listBanner= new ArrayList<>();
        List<DesktopAdvModel> listDesk= new ArrayList<>();
        Map<String,Object> map = new HashMap<>();

        //从第几条数据开始
        int iDisplayStart = Integer.parseInt(request.getParameter("iDisplayStart"));
        //每页显示的记录数
        int iDisplayLength = Integer.parseInt(request.getParameter("iDisplayLength"));
        //点击次数
        int sEcho = Integer.parseInt(request.getParameter("sEcho"));

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("iStart",iDisplayStart);
        paramMap.put("iLength",iDisplayLength);

        if(StringUtils.equals(initValue, Constants.Tab_Flag)){
            List<TabAdvModel> list = new ArrayList<>();
            try {
                listTab = tabAdvService.getTanAdvList(paramMap);
                List<TabAdvModel> listTabAll = tabAdvService.getTanAdvList(new HashMap<>());
                map.put("aData",listTab);
                if(CollectionUtils.isNotEmpty(listTab)){
                    map.put("sEcho ",sEcho+1);
                    map.put("iTotalDisplayRecords", listTabAll.size());//显示的条数
                    map.put("iTotalRecords",listTabAll.size());
                }
            } catch (Exception e) {
                logger.error("tab广告栏获取失败!"+e.getMessage());
            }
        }else if(StringUtils.equals(initValue, Constants.Banner_Flag)){
            List<BannerAdvModel> list = new ArrayList<>();
            try {
                listBanner = bannerAdvService.getBannerAdvList(paramMap);
                List<BannerAdvModel> listBannerAll = bannerAdvService.getBannerAdvList(new HashMap<>());
                map.put("aData",listBanner);
                if(CollectionUtils.isNotEmpty(listBanner)){
                    map.put("sEcho ",sEcho+1);
                    map.put("iTotalDisplayRecords", listBannerAll.size());//显示的条数
                    map.put("iTotalRecords",listBannerAll.size());
                }
            } catch (Exception e) {
                logger.error("banner广告栏获取失败!"+e.getMessage());
            }
        }else if(StringUtils.equals(initValue, Constants.Desk_Flag)){
            List<DesktopAdvModel> list = new ArrayList<>();
            try {
                listDesk = desktopAdvService.getDesktopAdvList(paramMap);
                List<DesktopAdvModel> listDeskAll = desktopAdvService.getDesktopAdvList(new HashMap<>());
                map.put("aData",listDesk);
                if(CollectionUtils.isNotEmpty(listDesk)){
                    map.put("sEcho ",sEcho+1);
                    map.put("iTotalDisplayRecords", listDeskAll.size());//显示的条数
                    map.put("iTotalRecords",listDeskAll.size());
                }
            } catch (Exception e) {
                logger.error("desk广告栏获取失败!"+e.getMessage());
            }
        }
        return map;
    }

    /**
     *  保存新增的广告
     */
    @RequestMapping("/saveTabAdv")
    @ResponseBody
    public BaseResult saveTabAdv(HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        String initValue = request.getParameter("initValue");
        String msg = "";
        if(StringUtils.equals("1",initValue)){
            msg = "Tab";
        }else if(StringUtils.equals("2",initValue)){
            msg = "Banner";
        }else if(StringUtils.equals("3",initValue)){
            msg = "Desk";
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile prodPicFile = multipartRequest.getFile("prodPic");
        Map<String,Object> prodPicMap = SystemUtil.saveFile(prodPicFile,multipartRequest);
        String prodPic = MapUtils.getString(prodPicMap,"savePath");

        String prodName = multipartRequest.getParameter("prodName");
        String prodUrl = multipartRequest.getParameter("prodUrl");
        String weight = multipartRequest.getParameter("weight");
        String prodRadio = multipartRequest.getParameter("prodRadio");

//        if(StringUtils.isAnyEmpty(prodPic,prodName,prodUrl,prodRadio)){
//            logger.error(msg+"广告保存失败:图片保存失败!");
//            baseResult.setSuccess(false);
//            return  baseResult;
//        }

        if(StringUtils.equals("1",initValue)){
            TabAdvModel tabAdvModel = new TabAdvModel();
            tabAdvModel.setAdvName(prodName);
            tabAdvModel.setAdvImage(prodPic);
            tabAdvModel.setAdvUrl(prodUrl);
            tabAdvModel.setWeight(weight);
            tabAdvModel.setCreateTime(new Date());
            tabAdvModel.setUpdateTime(new Date());
            tabAdvModel.setIsDelete("0");
            try {
                tabAdvService.saveTabAdv(tabAdvModel);
                //更改字典表，全局显示majt
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("Tab广告保存失败:数据库插入失败!");
                baseResult.setSuccess(false);
                return  baseResult;
            }
        }else if(StringUtils.equals("2",initValue)){
            MultipartHttpServletRequest multipartRequestB = (MultipartHttpServletRequest) request;
//            MultipartFile prodPicFileB = multipartRequest.getFile("prodPic");
//            Map<String,Object> prodPicMapB = SystemUtil.saveFile(prodPicFile,multipartRequest);
//            String prodPicB = MapUtils.getString(prodPicMap,"savePath");
//
            String prodUrlbb = multipartRequest.getParameter("prodUrlbb");
            String prodNameB = multipartRequest.getParameter("prodName");
            String prodUrlB = multipartRequest.getParameter("prodUrl");
            String weightB = multipartRequest.getParameter("weight");
//            String prodRadioB = multipartRequest.getParameter("prodRadio");
            BannerAdvModel bannerAdvModel = new BannerAdvModel();
            bannerAdvModel.setAdvName(prodNameB);
            bannerAdvModel.setAdvImage(prodUrlbb);
            bannerAdvModel.setAdvUrl(prodUrlB);
            bannerAdvModel.setWeight(weightB);
            bannerAdvModel.setCreateTime(new Date());
            bannerAdvModel.setUpdateTime(new Date());
            bannerAdvModel.setIsDelete("0");
            try {
                bannerAdvService.saveBannerAdv(bannerAdvModel);
                //更改字典表，全局显示majt
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("Banner广告保存失败:数据库插入失败!");
                baseResult.setSuccess(false);
                return  baseResult;
            }
        }else if(StringUtils.equals("3",initValue)){
            DesktopAdvModel desktopAdvModel = new DesktopAdvModel();
            desktopAdvModel.setAdvName(prodName);
            desktopAdvModel.setAdvImage(prodPic);
            desktopAdvModel.setAdvUrl(prodUrl);
            desktopAdvModel.setWeight(weight);
            desktopAdvModel.setCreateTime(new Date());
            desktopAdvModel.setUpdateTime(new Date());
            desktopAdvModel.setIsDelete("0");
            try {
                desktopAdvService.saveDesktopAdv(desktopAdvModel);
                //更改字典表，全局显示majt
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("Desk广告保存失败:数据库插入失败!");
                baseResult.setSuccess(false);
                return  baseResult;
            }
        }

        baseResult.setSuccess(true);
        return baseResult;
    }

    /**
     *  只保存APK
     */
    @RequestMapping("/saveTabAdvApk")
    @ResponseBody
    public BaseResult saveTabAdvApk(HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile prodPicaFile = multipartRequest.getFile("prodPica");
//        MultipartFile prodPicFile = multipartRequest.getFile("prodPic");
        Map<String,Object> prodPica = SystemUtil.saveFile(prodPicaFile,multipartRequest);
//        String prodName = multipartRequest.getParameter("prodName");
//        String prodUrl = multipartRequest.getParameter("prodUrl");
//        String prodRadio = multipartRequest.getParameter("prodRadio");

        if(StringUtils.isAnyEmpty(MapUtils.getString(prodPica,"savePath"))){
            logger.error("Apk保存失败:图片保存失败!");
            baseResult.setSuccess(false);
            return  baseResult;
        }else{
            logger.info("Apk保存成功:"+prodPica);
            baseResult.setSuccess(true);
            baseResult.setCode(MapUtils.getString(prodPica,"savePath"));
        }

        return baseResult;
    }

    /**
     *  只保存图片
     */
    @RequestMapping("/saveTabAdvImg")
    @ResponseBody
    public BaseResult saveTabAdvImg(HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        MultipartFile prodPicFile = multipartRequest.getFile("prodPic");
        MultipartFile prodPicFile = multipartRequest.getFile("prodPic");
//        Map<String,Object> prodPica = SystemUtil.saveFile(prodPicaFile,multipartRequest);
        Map<String,Object> prodPic = SystemUtil.saveFile(prodPicFile,multipartRequest);
//        String prodName = multipartRequest.getParameter("prodName");
//        String prodUrl = multipartRequest.getParameter("prodUrl");
//        String prodRadio = multipartRequest.getParameter("prodRadio");

        if(StringUtils.isAnyEmpty(MapUtils.getString(prodPic,"savePath"))){
            logger.error("Apk保存失败:图片保存失败!");
            baseResult.setSuccess(false);
            return  baseResult;
        }else{
            logger.info("Apk保存成功:"+prodPic);
            baseResult.setSuccess(true);
            baseResult.setCode(MapUtils.getString(prodPic,"savePath"));
        }

        return baseResult;
    }

    /**
     *  获取点击次数
     */
    @RequestMapping("/editClickNums")
    @ResponseBody
    public BaseResult editClickNums(HttpServletRequest request) {
        BaseResult<ClickDetails> baseResult = new BaseResult();
        String initValue = request.getParameter("initValue");
        String advId = request.getParameter("id");
        Integer flag = null;
        if(StringUtils.equals("2",initValue)){
            flag = 0;
        }else if(StringUtils.equals("3",initValue)){
            flag = 1;
        }else if(StringUtils.equals("1",initValue)){
            flag = 2;
        }
        String flagS = String.valueOf(flag);

        //获取对应id和flag的所有记录
        List<ClickDetails> clickDetailsList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("flag",flagS);
        map.put("advId",advId);

        try {
            clickDetailsList = clickService.selectByParam(map);
            if(CollectionUtils.isNotEmpty(clickDetailsList)){
                baseResult.setSuccess(true);
                baseResult.setList(clickDetailsList);
            }else{
                baseResult.setSuccess(false);
            }
        } catch (Exception e) {
            logger.error("查看点击详情失败!"+e.getMessage()+"flag:"+initValue);
            baseResult.setSuccess(false);
            return baseResult;
        }
        return baseResult;
    }
    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public BaseResult delete(HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        String id = request.getParameter("id");
        String initValue = request.getParameter("initValue");

        Map<String,Object> map = new HashMap<>();
        map.put("id",id);

        if(StringUtils.equals("1",initValue)){
            try {
                tabAdvService.delete(map);
                baseResult.setSuccess(true);
                return baseResult;
            } catch (Exception e) {
                logger.error("Tab删除失败");
                baseResult.setSuccess(false);
            }
        }else if(StringUtils.equals("2",initValue)){
            try {
                bannerAdvService.delete(map);
                baseResult.setSuccess(true);
                return baseResult;
            } catch (Exception e) {
                logger.error("Banner删除失败");
                baseResult.setSuccess(false);
            }
        }else if(StringUtils.equals("3",initValue)){
            try {
                desktopAdvService.delete(map);
                baseResult.setSuccess(true);
                return baseResult;
            } catch (Exception e) {
                logger.error("Desk删除失败");
                baseResult.setSuccess(false);
            }
        }

        return baseResult;
    }

    /**
     *  获取单个广告信息
     */
    @RequestMapping("/editTabV")
    @ResponseBody
    public BaseResult<TabAdvModel> editTabV(HttpServletRequest request, @RequestParam Integer id) {
        BaseResult<TabAdvModel> baseResult = new BaseResult();

        Map<String,Object> map = new HashMap<>();
        map.put("id",id);

        try {
            TabAdvModel tabAdvModel = tabAdvService.selectByParam(map);
            baseResult.setSuccess(true);
            baseResult.setT(tabAdvModel);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("编辑广告失败!");
            baseResult.setSuccess(false);
            return baseResult;
        }

        return baseResult;
    }

    /**
     *  更新单个广告信息
     */
    @RequestMapping("/editTab")
    @ResponseBody
    public BaseResult<TabAdvModel> editTab(HttpServletRequest request, @RequestParam Integer id) {
        BaseResult<TabAdvModel> baseResult = new BaseResult();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        MultipartFile prodPicaFile = multipartRequest.getFile("prodPica");
//        MultipartFile prodPicFile = multipartRequest.getFile("prodPic");
//        Map<String,Object> prodPicMap = SystemUtil.saveFile(prodPicFile,multipartRequest);
//        String prodPic = MapUtils.getString(prodPicMap,"savePath");
        String prodName = multipartRequest.getParameter("prodName");
        
        //解决图片image没有更新的bug，如果为空就不更新
        MultipartFile prodPicFile = multipartRequest.getFile("prodPic");
        Map<String,Object> prodPicMap = SystemUtil.saveFile(prodPicFile,multipartRequest);
        String prodPic = MapUtils.getString(prodPicMap,"savePath");

        String prodUrl = multipartRequest.getParameter("prodUrl");
        String weight = multipartRequest.getParameter("weight");
//        String prodRadio = multipartRequest.getParameter("prodRadio");

        Map<String,Object> map = new HashMap<>();
        map.put("id",id);

        TabAdvModel tabAdvModel = new TabAdvModel();
        tabAdvModel.setAdvImage(prodPic);
        tabAdvModel.setAdvName(prodName);
        tabAdvModel.setAdvUrl(prodUrl);
        tabAdvModel.setId(id);
        tabAdvModel.setUpdateTime(new Date());
        tabAdvModel.setWeight(weight);
        try {
            tabAdvService.updateTab(tabAdvModel);
            baseResult.setSuccess(true);
            baseResult.setT(tabAdvModel);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更新广告失败!");
            baseResult.setSuccess(false);
            return baseResult;
        }

        return baseResult;
    }
}
